package com.cheyun.netsalev3.viewmodel

import android.content.Intent
import android.content.pm.PackageManager
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ObservableField
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.paging.PagedList
import androidx.work.Data
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import com.cheyun.netsalev3.R
import com.cheyun.netsalev3.bean.CustomListParam
import com.cheyun.netsalev3.bean.Row
import com.cheyun.netsalev3.bean.Search
import com.cheyun.netsalev3.bean.basedata.NormalList
import com.cheyun.netsalev3.dao.SearchDao
import com.cheyun.netsalev3.repository.HomeCustomerPageRepository
import com.cheyun.netsalev3.repository.SearchRepository
import com.cheyun.netsalev3.utils.CommonFunc
import com.cheyun.netsalev3.utils.FunctionUtils
import com.cheyun.netsalev3.utils.MySharedPreferences
import com.cheyun.netsalev3.utils.api.NetworkState
import com.cheyun.netsalev3.view.defeatdetails.DefeatDetailsActivity
import com.cheyun.netsalev3.widget.BaseDialog
import com.cheyun.netsalev3.workers.SearchDatabaseWorker
import com.cheyunkeji.er.MyApplication
import com.cheyunkeji.er.utils.ToastUtil
import com.umeng.commonsdk.stateless.UMSLEnvelopeBuild.mContext


/**
 * @author Michael
 * @date  2018/12/17 - 14:45.
 */
class CustomerItemFragmentViewModel(var repository: HashMap<String, HomeCustomerPageRepository>) : BaseViewModel(), BaseDialog.BaseDialogListener {

    var Poplists = MutableLiveData<List<CustomListParam>>()
    var clueColumn = MySharedPreferences.getClueRightColumn()

    var sort = MutableLiveData<String>("followtime")
    var order = MutableLiveData<String>("desc")

    var nkey = "archive.index";
    private var names = arrayListOf(
            CustomListParam("首选车", 4, 0, "specname"),
            CustomListParam("业务类型", 0, 0, "infotypename"),
            CustomListParam("信息渠道", 1, 0, "infoplacename"),
            CustomListParam("信息来源", 2, 0, "infosourcename"))


    //历史搜索相关
    var keyword = ObservableField<String>("")
    var searchRepository: SearchRepository? = null
    var searchlist :LiveData<List<Search>>? = null
    fun initSearchRepository(searchDao: SearchDao){
        searchRepository = SearchRepository(searchDao)
        searchlist = searchRepository?.getlist()
    }
    fun search(nkey:String) {
        if (keyword.get().isNullOrBlank()) {

        } else {
            val myData = Data.Builder()
                    .putString("key", keyword.get().toString())
                    .build()
            val compressionWork = OneTimeWorkRequestBuilder<SearchDatabaseWorker>()
                    .setInputData(myData).build()
            WorkManager.getInstance().enqueue(compressionWork)
            searchClue(nkey, keyword.get().toString())
        }
    }
    fun deleteTabe(view: View) {
        searchRepository?.deleteTabe()
    }
    fun searchItem(nkey:String,pos:Int) {
        var item = searchlist?.value?.get(pos)
        searchClue(nkey, item?.key!!)
    }
    fun searchClue(nkey:String,key:String){
        var hashMap = HashMap<String, String>()
        repository[nkey]?.map!!.forEach {
            hashMap[it.key] = it.value
        }
        hashMap.put("keyword",key)
        hashMap.put("sort","followtime")
        hashMap.put("order","desc")
        repository[nkey]?.changeMap(hashMap)
        repository[nkey]?.dataSourceFactory?.sourceLiveData?.value?.invalidate()
    }
    fun onBack(view:View){
        myFinish()
    }

    /**
     * 点击item
     */
    fun onClickItem(view: View, item: Row) {
        var intent = Intent(view.context, DefeatDetailsActivity::class.java)
        intent.putExtra("tid", item.tid)
        intent.putExtra("nkey", item.neky)
        view.context.startActivity(intent)
    }

    fun onToWeixin(view:View,item:Row){
        if (item.phone.indexOf("*") == -1) {
            CommonFunc.copy(view.context, item.phone)
            ToastUtil.showToast("复制成功")
        } else {
            ToastUtil.showToast("当前号码不能复制")
        }
        FunctionUtils.startAppWithPackageName(view.context,"com.tencent.mm")
    }

    fun onCallTel(view:View,item:Row){
        if (item.phone.indexOf("*") == -1) {
            FunctionUtils.callPhone(view.context, item?.phone!!)
        } else {
            ToastUtil.showToast("当前号码不能拨打")
        }
    }

    fun onSetFocus(view:View,item:Row){
        var moth: () -> Unit = {
            if (item.isfocus == 1) {
                item.isfocus = 0
                ToastUtil.toastShortMessage("已取消标记为重点客户")
            } else {
                item.isfocus = 1
                ToastUtil.toastShortMessage("已标记为重点客户")
            }
        }
        repository[nkey]?.setIsFocus(item.tid.toString(),item.isfocus,moth)
    }

    protected var TAG = javaClass.simpleName

    //选中的列表数据
    var pagedlist = HashMap<String, LiveData<PagedList<Row>>>()
    var hashMap = HashMap<String, LiveData<NetworkState>>()
    var totlelist = HashMap<String, LiveData<Int>>()
    var toplist = HashMap<String, LiveData<List<NormalList>>>()
    var focus_total = HashMap<String, LiveData<Int>>()
    //选择大类
    var filterType = MutableLiveData<Int>()

    init {
        Poplists.postValue(names)

        for (key in repository.keys) {
            repository[key]?.apply {
                pagedlist[key] = this.loadAndroidData(null)
            }
        }
    }

    init {
        for (item in repository.keys) {
            pagedlist[item]?.apply {
                hashMap[item] = Transformations.switchMap(this) { repository[item]!!.networkState }!!
                totlelist[item] = Transformations.switchMap(this) { repository[item]!!.total }!!
                toplist[item] =  Transformations.switchMap(this) { repository[item]!!.toplist }!!
                focus_total[item] =  Transformations.switchMap(this) { repository[item]!!.focus_total }!!
            }
        }
    }

    var poplists = MySharedPreferences.getListItem()

    //自定义选项返回
    fun onResult(list: List<CustomListParam>) {
        poplists.clear()
        poplists.addAll(list)
        for (i in pagedlist.values) {
            i.value?.apply {
                for (row in i.value!!) {
                    //默认全部为没选中
                    for (d in row.hashMap.values) {
                        d.IsSelect = false
                    }
                    //筛选返回数据 设置为选中
                    for (cus in list) {
                        row.hashMap[cus.key]?.IsSelect = true
                    }
                }
            }
        }
    }
    fun initData(nkey: String) {
        Log.i(TAG,"initData ,"+ nkey)
        repository[nkey]?.apply {
            this.setEanbleLoad(true)
            this.dataSourceFactory.sourceLiveData.value?.invalidate()
        }
    }

    fun onFilter(view: View, type: Int) {
//        if (type == filterType.value) {
//            return
//        }
        filterType.postValue(type)
        view.visibility = View.VISIBLE
        var filters = HashMap<String, String>()
        // type 1 待跟进， 2 持续邀约中  3 邀约成功  4 试驾成功
        if(type == 0){
            filters.put("sort","followtime")
            filters.put("order","desc")
        }
        if(type == 1) filters.put("followstate","2604")
        if(type == 2) filters.put("followstate","2605")
        if(type == 3) filters.put("followstate","2606")
        if(type == 4) filters.put("followstate","2610")
        refresh(nkey,filters)
    }

    fun onChangeSort(s:String){
        sort.postValue(s)
        var filters = repository[nkey]?.map as HashMap
        filters.put("sort",sort.value!!)
        refresh(nkey,filters)
    }

    fun onChangeOrder(view:View){
        if(order.value.equals("desc"))
            order.postValue("asc")
        else
            order.postValue("desc")
        var filters = repository[nkey]?.map as HashMap
        filters.put("order",order.value!!)
        refresh(nkey,filters)
    }

    /**
     * 刷新
     */
//    fun refresh(nkey: String,ownerUid:String) {
//        var hashMap = HashMap<String, String>()
////        var hashMap = repository[nkey]?.map
//        repository[nkey]?.map!!.forEach {
//            hashMap[it.key] = it.value
//        }
//        if(ownerUid.isNotEmpty()) {
//            hashMap["owneruid"] = ownerUid
//            repository[nkey]?.changeMap(hashMap)
//        }else{
//            if(hashMap.containsKey("owneruid")){
//                hashMap.remove("owneruid")
//                repository[nkey]?.changeMap(hashMap)
//            }
//        }
//        repository[nkey]?.dataSourceFactory?.sourceLiveData?.value?.invalidate()
//    }

    /**
     * 刷新
     */
    fun refresh(nkey: String, filters: HashMap<String, String>? = null) {
        if (filters != null) {
            repository[nkey]?.changeMap(filters!!)
        }
        repository[nkey]?.dataSourceFactory?.sourceLiveData?.value?.invalidate()
    }

    fun onChangeLevel(view: View, item: Row) {
        var content = view.context
        if (content is AppCompatActivity) {
            val newFragment = BaseDialog()
            newFragment.listener = this
            newFragment.show(content.supportFragmentManager, "missiles")
        }
    }


    override var title: String = "自定义选项"
    override var content: String? = null
    override var layoutId: Int = R.layout.base_dialog_list_item
    override var list: MutableLiveData<List<*>>
        get() {
            //筛选数据  根据列表数据把弹窗数据（Poplists）对应位置设置为选中
            for (i in 0 until Poplists.value?.size!!) {
                Poplists.value?.get(i)?.IsSelect = if (Poplists.value?.get(i)?.key.equals(clueColumn)) true else false
            }
            return Poplists as MutableLiveData<List<*>>
        }
        set(value) {
            list = value
        }

    override fun onClickCancel(view: View) {
    }

    override fun onClickOk(view: View) {
        Poplists.postValue(names)
        var name = names.find { it.IsSelect == true }
        if (name != null) {
            if (!clueColumn.equals(name.key)) {
                MySharedPreferences.setClueRightColumn(name.key)
                clueColumn = name.key

                for (i in pagedlist.values) {
                    i.value?.apply {
                        for (row in i.value!!) {
                            when (clueColumn) {
                                "dateline" -> row.clueCustomerColumn = if (row.dateline == null) "" else row.dateline
                                "infotypename" -> row.clueCustomerColumn = if (row.infotypename == null) "" else row.infotypename
                                "infoplacename" -> row.clueCustomerColumn = if (row.infoplacename == null) "" else row.infoplacename
                                "infosourcename" -> row.clueCustomerColumn = if (row.infosourcename == null) "" else row.infosourcename
                                "brandname" -> row.clueCustomerColumn = if (row.brandname == null) "" else row.brandname
                                "specname" -> row.clueCustomerColumn = if (row.specname == null) "" else row.specname
                                "region" -> row.clueCustomerColumn = if (row.region == null) "" else row.region
                                "exteriorname" -> row.clueCustomerColumn = if (row.exteriorname == null) "" else row.exteriorname
                                "interiorname" -> row.clueCustomerColumn = if (row.interiorname == null) "" else row.interiorname
                                "customerlevelname" -> row.clueCustomerColumn = if (row.customerlevelname == null) "" else row.customerlevelname
                            }
//                            com.orhanobut.logger.Logger.d("clueCustomerColumn %s, value:%s",clueColumn,row.clueCustomerColumn)
                        }
                    }
                }
            }
        }
    }

    override fun onClickItem(view: View, param: Any) {
        for (item in names) {
            item.IsSelect = false
        }
        if (param is CustomListParam) {
            param.IsSelect = !param.IsSelect
        }
    }
}